from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
# 正则表达式(regular expression)主要功能是从字符串(string)中通过特定的模式(pattern)，搜索想要找到的内容。
import re
from rest_framework_jwt.settings import api_settings


class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = '__all__'


class UserLoginSerializers(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['username', 'password']

    def validate(self, data):
        username = data.get('username', None)
        password = data.get('password', None)

        # if re.match('^1[3-9][0-9]{9]$', username):
        #     user = User.objects.filter(mobile=username).first()
        #
        # elif re.match('^.+@.+$', username):
        #     user = User.objects.filter(email=username).first()
        #
        # else:
        user = authenticate(username=username, password=password)

        if user:
            if user.check_password(password):
                payload = api_settings.JWT_PAYLOAD_HANDLER(user)
                # .encode 生成token; .decode token解密
                token = api_settings.JWT_ENCODE_HANDLER(payload)
                self.context['token'] = token
                self.context['username'] = user.username
                return data
            else:
                raise ValidationError('密码错误')
        else:
            raise ValidationError('用户不存在')


from rest_framework.validators import UniqueValidator


class UserRegisterSerializer(serializers.ModelSerializer):
    username = serializers.CharField(required=True, allow_blank=False,
                                     validators=[UniqueValidator(queryset=User.objects.all(),
                                                                 message='该用户已经存在！')])
    password = serializers.CharField(
        style={"input_type": "password"}, help_text="密码", label="密码", write_only=True,
    )

    class Meta:
        model = User
        fields = ('username', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        user.set_password(validated_data["password"])
        user.save()
        return user
